﻿using System;

namespace SimpleServiceBus.Bus
{
    // <summary>
    /// Attribute to indicate that a message does (or does not) need to be recoverable.
    /// </summary>
    /// <remarks>
    /// A recoverable message is stored locally at every step along the route so that in the event of
    /// a failure of a machine along the route a copy of the message will be recovered and
    /// delivery will continue when the machine is brought back online. Unless this attribute is applied
    /// with a value of 'false', each message will be treated as Recoverable by default.</remarks>
    [AttributeUsage(AttributeTargets.Class)]
    public class RecoverableAttribute : Attribute
    {
        public RecoverableAttribute()
        {
        }

        public RecoverableAttribute(bool recoverable)
        {
            Recoverable = recoverable;
        }

        public bool Recoverable = true;

        public static bool IsRecoverable(object message)
        {
            if (message == null)
                return false;
            object[] attributes = message.GetType().GetCustomAttributes(typeof (RecoverableAttribute), false);
            if (attributes.Length > 0)
                return ((RecoverableAttribute) attributes[0]).Recoverable;
            return true;

        }
    }


    /// <summary>
    /// Attribute to indicate that a message has a period of time 
    /// in which to be received.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class TimeToBeReceivedAttribute : Attribute
    {
        private readonly TimeSpan timeToBeReceived = TimeSpan.MaxValue;

        /// <summary>
        /// Sets the time to be received to be unlimited.
        /// </summary>
        public TimeToBeReceivedAttribute()
        {
        }

        /// <summary>
        /// Sets the time to be received.
        /// </summary>
        /// <param name="timeSpan">A timespan that can be interpreted by <see cref="TimeSpan.Parse"/>.</param>
        public TimeToBeReceivedAttribute(string timeSpan)
        {
            timeToBeReceived = TimeSpan.Parse(timeSpan);
        }

        /// <summary>
        /// Gets the maximum time in which a message must be received.
        /// </summary>
        /// <remarks>
        /// If the interval specified by the TimeToBeReceived property expires before the message 
        /// is received by the destination of the message the message will automatically be cancelled.
        /// </remarks>
        public TimeSpan TimeToBeReceived
        {
            get { return timeToBeReceived; }
        }
    }
}